package org.dromara.code.service.impl

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import org.dromara.code.domain.CodeProduct
import org.dromara.code.domain.bo.CodeProductBo
import org.dromara.code.domain.vo.CodeProductVo
import org.dromara.code.mapper.CodeProductMapper
import org.dromara.code.service.ICodeProductService
import org.dromara.common.core.utils.MapstructUtils
import org.dromara.common.core.utils.hasText
import org.dromara.common.mybatis.core.page.PageQuery
import org.dromara.common.mybatis.core.page.TableDataInfo
import org.springframework.stereotype.Service

/**
 * 一物一码产品类目Service业务层处理
 *
 * @author Blutter J
 * @date 2025-08-07
 */
@Service
class CodeProductServiceImpl(
    private val baseMapper: CodeProductMapper
): ICodeProductService {

    override fun queryById(id: Long): CodeProductVo? {
        return baseMapper.selectVoById(id)
    }
    override fun queryPageList(bo: CodeProductBo, pageQuery: PageQuery): TableDataInfo<CodeProductVo> {
        val lqw = buildQueryWrapper(bo)
        val result = baseMapper.selectVoPage<Page<CodeProductVo>>(pageQuery.build(), lqw)
        return TableDataInfo.build(result)
    }
    override fun queryList(bo: CodeProductBo): List<CodeProductVo> {
        val lqw = buildQueryWrapper(bo)
        return baseMapper.selectVoList(lqw)
    }

    override fun insertByBo(bo: CodeProductBo): Boolean {
        val add = MapstructUtils.convert(bo, CodeProduct::class.java)
        validEntityBeforeSave(add)
        val flag = baseMapper.insert(add) > 0
        if (flag)
            bo.id = add.id
        return flag
    }

    override fun updateByBo(bo: CodeProductBo): Boolean {
        val update = MapstructUtils.convert(bo, CodeProduct::class.java)
        validEntityBeforeSave(update)
        return baseMapper.updateById(update) > 0
    }

    override fun deleteWithValidByIds(ids: List<Long>, isValid: Boolean): Boolean {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0
    }

    private fun validEntityBeforeSave(entity: CodeProduct) {
        //TODO 做一些数据校验,如唯一约束
    }

    private fun buildQueryWrapper(bo: CodeProductBo): LambdaQueryWrapper<CodeProduct> {
        val lqw = Wrappers.lambdaQuery<CodeProduct>()
        lqw.orderByAsc(CodeProduct::getId)
        lqw.like(bo.productName.hasText(), CodeProduct::getProductName, bo.productName)
        lqw.eq(bo.orderNum != null, CodeProduct::getOrderNum, bo.orderNum)
        lqw.eq(bo.dataJson.hasText(), CodeProduct::getDataJson, bo.dataJson)
        return lqw
    }
}
